package com.smallkingson.ylib.core.utils;

import android.content.pm.Signature;
import android.text.TextUtils;
import java.io.File;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.Cursor;
import android.graphics.Rect;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.os.storage.StorageManager;
import android.provider.MediaStore;
import android.telephony.TelephonyManager;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;

import com.smallkingson.ylib.core.Yr;
import com.smallkingson.ylib.view.utils.YViews;

public class YSystems {

  public static String getPathFromUri(Context context, Uri originalUri) {

    ContentResolver resolver = context.getContentResolver();
    String[] proj = {MediaStore.Images.Media.DATA};
    Cursor cursor = resolver.query(originalUri, proj, null, null, null);
    // 按我个人理解 这个是获得用户选择的图片的索引值
    int column_index = cursor
        .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    // 最后根据索引值获取图片路径
    String path = cursor.getString(column_index);
    return path;
  }

  /**
   * <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/> <uses-permission
   * android:name="android.permission.CHANGE_WIFI_STATE"/> <uses-permission
   * android:name="android.permission.WAKE_LOCK"/>
   */
  public static void setWifiEnable(Context context, boolean on) {
    WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
//        if (wifiManager.isWifiEnabled()) {
    wifiManager.setWifiEnabled(on);
  }

  public static boolean isWifiEnable(Context context) {
    WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    return wifiManager.isWifiEnabled();
  }

  public static void toggleMobileData(Context context) {

    if (isMobileDataEnabled(context)) {
      setMobileData(context, false);
    } else {
      setMobileData(context, true);
    }
  }

  /**
   * 设置手机的移动数据 <uses-permission android:name="android.permission.MODIFY_PHONE_STATE"/>
   * <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/> <uses-permission
   * android:name="android.permission.ACCESS_NETWORK_STATE"/>
   */
  public static void setMobileData(Context pContext, boolean pBoolean) {

    try {
      ConnectivityManager mConnectivityManager = (ConnectivityManager) pContext
          .getSystemService(Context.CONNECTIVITY_SERVICE);
      Class ownerClass = mConnectivityManager.getClass();
      Class[] argsClass = new Class[1];
      argsClass[0] = boolean.class;
      Method method = ownerClass.getMethod("setMobileDataEnabled", argsClass);
      method.invoke(mConnectivityManager, pBoolean);
    } catch (Exception e) {
      Yr.logError(e);
      System.out.println("移动数据设置错误: " + e.toString());
    }
  }

  public static boolean isMobileDataEnabled(Context context) {
    try {
      ConnectivityManager mConnectivityManager = (ConnectivityManager) context
          .getSystemService(Context.CONNECTIVITY_SERVICE);
      Class ownerClass = mConnectivityManager.getClass();
      Method getMobileDataEnabled = ownerClass.getDeclaredMethod("getMobileDataEnabled");
      getMobileDataEnabled.setAccessible(true);
      Object invoke = getMobileDataEnabled.invoke(mConnectivityManager);
      return (boolean) invoke;
    } catch (Exception e) {
      Yr.logError(e);
    }
    return false;
  }

  public static void openBrowser(Context context, String url) {

    // urlText是一个文本输入框，输入网站地址

    // Uri 是统一资源标识符

    Uri uri = Uri.parse(url);

    Intent intent = new Intent(Intent.ACTION_VIEW, uri);

    context.startActivity(intent);

  }

  public static void setScreenOffTimeOut(Context context, int time) {
    android.provider.Settings.System
        .putInt(context.getContentResolver(), android.provider.Settings.System
            .SCREEN_OFF_TIMEOUT, time);
  }

  public static void startActivityToAccessibilitySettings(Context context) {
    Intent killIntent = new Intent("android.settings.ACCESSIBILITY_SETTINGS");
    context.startActivity(killIntent);
  }

  public static void hideInput(Activity activity) {
    // 输入法管理
    InputMethodManager manager = (InputMethodManager) activity
        .getSystemService(Context.INPUT_METHOD_SERVICE);
    if (activity.getWindow().getAttributes().softInputMode
        != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
      if (activity.getCurrentFocus() != null) {
        manager.hideSoftInputFromWindow(activity.getCurrentFocus()
            .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
      }
    }
  }

  public static String getCurrentTime(String pattern) {

    System.currentTimeMillis();

    Date date = new Date(System.currentTimeMillis());

    SimpleDateFormat format = new SimpleDateFormat(pattern);

    return format.format(date);
  }

  public static String getCurrentTime() {

    return getCurrentTime("yyyy年MM月dd日mm分ss秒");
  }

  public static boolean isTop(Context context, Class<? extends Activity> activityClass) {
    ActivityManager manager = (ActivityManager) context
        .getSystemService(Context.ACTIVITY_SERVICE);
    List<ActivityManager.RunningTaskInfo> runningTaskInfos = manager.getRunningTasks(1);

    String cmpNameTemp = null;

    if (null != runningTaskInfos) {
      cmpNameTemp = (runningTaskInfos.get(0).topActivity).toString(); // 这里cmpNameTemp是package
    }
    Yr.i(cmpNameTemp);
    if (null == cmpNameTemp) {
      return false;
    }
    return cmpNameTemp.contains(activityClass.getSimpleName()); // 如果cmdName是package
  }

  public static boolean isSoftInputShow(Activity activity) {

    // 虚拟键盘隐藏 判断view是否为空
    View view = activity.getWindow().peekDecorView();
    if (view != null) {
      // 隐藏虚拟键盘
      InputMethodManager inputmanger = (InputMethodManager) activity
          .getSystemService(Activity.INPUT_METHOD_SERVICE);

      return inputmanger.isActive();
    }
    return false;
  }

  public static int getSoftInputHeight(View v) {

    Rect r = new Rect();
    v.getRootView().getWindowVisibleDisplayFrame(r);
    int screenHeight = v.getRootView().getHeight();
    int heightDifference = screenHeight - (r.bottom - r.top)
        - YViews.STATUSBAR_HEIGHT;
    return heightDifference;
  }

  public static String getVersion(Context context) {
    try {
      PackageManager manager = context.getPackageManager();
      PackageInfo info = manager.getPackageInfo(context.getPackageName(),
          0);
      String version = info.versionName;
      return version;
    } catch (Exception e) {
      Yr.logError(e);
      e.printStackTrace();
    }
    return "-1.0";
  }

  public static int getVersionCode(Context context) {
    PackageManager manager = context.getPackageManager();
    PackageInfo info = null;
    try {
      info = manager.getPackageInfo(context.getPackageName(), 0);
      int version = info.versionCode;
      return version;
    } catch (NameNotFoundException e) {
      Yr.logError(e);
    }

    return -1;
  }

  public static String getIMEI(Context context) {
    TelephonyManager telephonyManager = (TelephonyManager) context
        .getSystemService(Context.TELEPHONY_SERVICE);
    try {
      return telephonyManager.getDeviceId();
    } catch (Exception e) {
      Yr.e(e);
    }
    return "";
  }
  public static String getIMSI(Context context) {
    TelephonyManager telephonyManager = (TelephonyManager) context
        .getSystemService(Context.TELEPHONY_SERVICE);
    try {
      return telephonyManager.getSubscriberId();
    } catch (Exception e) {
      Yr.e(e);
    }
    return "";
  }
  //	public static void registerBatteryReceiver(final YActivity activity,
//			OnBatteryChangeListener onBatteryChangeListener) {
//
//		final BroadcastReceiver receiver = new BroadcastReceiver() {
//			@Override
//			public void onReceive(Context context, Intent intent) {
//
//				// TODO Auto-generated method stub
//				// 判断它是否是为电量变化的Broadcast Action
//				if (Intent.ACTION_BATTERY_CHANGED.equals(intent.getAction())) {
//					// 获取当前电量
//					int level = intent.getIntExtra("level", 0);
//					// 电量的总刻度
//					int scale = intent.getIntExtra("scale", 100);
//					// 把它转成百分比
//					// tv.setText("电池电量为" + ((level * 100) / scale) + "%");
//				}
//			}
//		};
//		activity.registerReceiver(receiver, new IntentFilter(
//				Intent.ACTION_BATTERY_CHANGED));
//		activity.addOnStateChangeAdapter(new OnStateChangeAdapter() {
//			@Override
//			public void onDestroy() {
//				super.onDestroy();
//				activity.unregisterReceiver(receiver);
//				activity.removeOnStateChangeListener(this);
//			}
//		});
//	}

  /**
   * 获取所有外存卡地址
   */
  public static List<String> getSdPaths(Context context) {
    StorageManager sm = (StorageManager) context.getSystemService(Context.STORAGE_SERVICE);
    List<String> paths = new ArrayList<String>();
    try {
      String[] volumePaths = (String[]) sm.getClass().getMethod("getVolumePaths").invoke(sm);
      for (int i = 0; i < volumePaths.length; i++) {
        String status = (String) sm.getClass().getMethod("getVolumeState", String.class)
            .invoke(sm, volumePaths[i]);
        if (status.equals(android.os.Environment.MEDIA_MOUNTED)) {
          paths.add(volumePaths[i]);
        }
      }
    } catch (Exception e) {
      Yr.logError(e);
    }
    return paths;
  }

  public static interface OnBatteryChangeListener {

    void onBattery(int level, int scale);
  }


  /**
   * 安装
   *
   * @param context 接收外部传进来的context
   */
  public static void install(Context context, String path) {
    // 核心是下面几句代码
    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setDataAndType(Uri.fromFile(new File(path)),
        "application/vnd.android.package-archive");
    context.startActivity(intent);
  }

  public static String getProcessName(Context context) {
    ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    List<ActivityManager.RunningAppProcessInfo> runningAppProcesses = am.getRunningAppProcesses();
    if (runningAppProcesses == null) {
      return "";
    }

    for (ActivityManager.RunningAppProcessInfo runningAppProcess : runningAppProcesses) {
      if (runningAppProcess.pid == android.os.Process.myPid()
          && !TextUtils.isEmpty(runningAppProcess.processName)) {
        return runningAppProcess.processName;
      }
    }
    return "";
  }

  public static String getSignature(Context context)
  {
    try {
      /** 通过包管理器获得指定包名包含签名的包信息 **/
      PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), PackageManager.GET_SIGNATURES);
      /******* 通过返回的包信息获得签名数组 *******/
      Signature[] signatures = packageInfo.signatures;
      /******* 循环遍历签名数组拼接应用签名 *******/
      return signatures[0].toCharsString();
      /************** 得到应用签名 **************/
    } catch (PackageManager.NameNotFoundException e) {
      e.printStackTrace();
    }
    return null;
  }
}
